from typing import Dict

from django.db.models import QuerySet
from django.shortcuts import render, HttpResponse, redirect, HttpResponseRedirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
from .models import Issue, Answer, Comment
from .forms import IssueForm, AnswerForm
from django.db.models import Q
from firstapp.forms import CommentForm
# Create your views here.


@login_required
def index(request):
    kmap: Dict[str, QuerySet[Answer]] = {}
    if request.method == 'GET':
        answers = Answer.objects.all()
        kmap['answers'] = answers
    if request.method == 'POST':
        form = IssueForm(data=request.POST)
        for i in request.POST.items():
            print(i)
        print('execute to this')
        if form.is_valid():
            title = form.cleaned_data['title']
            description = form.cleaned_data['description']
            anonymity = form.cleaned_data['anonymity']
            issue = Issue(belong_to=request.user, title=title, description=description, anonymity=anonymity)
            issue.save()
            print('execute to save')
            return redirect(to='index')
        else:
            print(form.errors)
            print('Form is invalid!!!')
    return render(request, 'index.html', kmap)

    # kmap: Dict[str, Union[QuerySet[Article], Article]] = {}
    # articles = Article.objects.all().order_by('-create_time')[:10]
    # kmap['articles'] = articles
    # hot_articles = Article.objects.all().order_by('-like')[:10]
    # kmap['hot_articles'] = hot_articles
    # return render(request, 'index.html', kmap)


# def third(request):
#     kmap = {}
#     articles = Article.objects.all()
#     kmap['articles'] = articles
#     article_name = request.GET.get('name')
#     if article_name:
#         try:
#             current_article = Article.objects.get(headline=article_name)
#         except :
#             print(f'blog { article_name } does not exist!')
#             current_article = articles[0]
#     elif len(articles) > 0:
#         current_article = articles[0]
#     kmap['current_article'] = current_article
#     form = CommentForm()
#     kmap['form'] = form
#     return render(request, 'blog.html', kmap)


def user_register(request):
    if request.method == 'GET':
        form = UserCreationForm()
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        for i in request.POST.items():
            print(i)
        if form.is_valid():
            form.save()
            # return HttpResponse('Register Success')
            return redirect(to="login")
    content = {'form': form, 'status': 'register'}
    return render(request, 'new_login_register.html', content)


def user_login(request):
    if request.method == 'GET':
        form = AuthenticationForm()
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        print(form.is_valid(), form.error_messages)
        if form.is_valid():
            login(request, form.get_user())
            return redirect(to="index")
    content = {'form': form, 'status': 'login'}
    return render(request, 'new_login_register.html', content)


@login_required
def user_logout(request):
    logout(request)
    return HttpResponse("Logout Success")


@login_required
def answer(request, issue_id):
    if request.method == 'POST':
        form = AnswerForm(data=request.POST)
        for i in request.POST.items():
            print(i)
        if form.is_valid():
            print('enter if', request.POST)
            # issue_id = form.cleaned_data['issue']
            answer_obj = form.cleaned_data['answer']
            anonymity = form.cleaned_data['anonymity']
            print(issue_id, answer_obj, anonymity, '--------------------')
            issue_obj = Issue.objects.get(id=issue_id)
            answer_obj = Answer(belong_to=request.user, issue=issue_obj, answer=answer_obj, anonymity=anonymity)
            answer_obj.save()
            print('This')
            return redirect(to="answer", issue_id=issue_id)
    issue = Issue.objects.get(id=issue_id)
    kmap = {'issue': issue}
    return render(request, 'new_answer.html', kmap)


@login_required
def submit_comment(request, answer_id):
    if request.method == "POST":
        form = CommentForm(data=request.POST)
        answer = Answer.objects.filter(id=answer_id)
        if form.is_valid() and len(answer) > 0:
            user = request.user
            content = form.cleaned_data['comment']
            comment = Comment(belong_to=user, content=content, answer=answer.first())
            comment.save()
            return redirect(to="answer", issue_id=answer.first().issue.id)
        print(form.errors)
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
    return HttpResponseRedirect(request.META['HTTP_REFERER'])
